<template>
    <div class="news-dict-container">
  
  <!--    内容分类模块列表-->
      <el-card>
        <div slot="header" class="clearfix">
          <span>内容分类模块列表</span>
          <el-button
              style="float: right; margin-top: -5px"
              type="primary"
              @click="handleAdd"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </div>
        <!-- 数据列表区域 -->
        <el-table
            :data="processedTableData"
            border
            style="width: 100%"
            row-key="categoryId"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="categoryName" label="分类名称">
            <template #default="{ row }">
              <span :style="{ paddingLeft: (row.level * 20) + 'px' }">
                <i :class="row.children ? 'el-icon-folder' : 'el-icon-document'" style="margin-right: 5px;"></i>
                {{ row.categoryName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
          <el-table-column prop="status" label="是否启用">
            <template #default="{ row }">
              <el-tooltip :content="row.isActive === 1 ? '正常' : '禁用'" placement="top">
                <el-switch
                    v-model="row.isActive"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="newStatus => handleSwitchChange(row, newStatus)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              align="center"
          >
            <template #default="{ row }">
              <el-link type="danger" @click="handleDelete(row)">删除</el-link>
              <el-divider direction="vertical" />
              <el-link type="success" @click="handleEdit(row)">编辑</el-link>
              <el-divider direction="vertical" v-if="!row.parentId" />
              <el-link type="primary" @click="handleAddChild(row)" v-if="!row.parentId">添加子类</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <!-- 分页组件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[6, 12, 20, 30]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right"
      ></el-pagination>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog
          :title="formTitle"
          v-model="dialogVisible"
          width="50%"
      >
        <el-form :model="form" label-width="120px">
          <el-form-item label="父分类" v-if="isAddingChild">
            <el-input v-model="parentCategoryName" disabled></el-input>
          </el-form-item>
          <el-form-item label="分类名称">
            <el-input v-model="form.categoryName" placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input
                type="textarea"
                v-model="form.description"
                placeholder="请输入描述信息"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-switch
                v-model="form.isActive"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"></el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from '@/utils/request';
  export default {
    name: 'NewsDict',
    data() {
      return {
        // 表格数据
        tableData: [],
        processedTableData: [],
        // 分页总条数
        total: 0,
        current:1,
        size:20,
        // 选中项
        selectedRows: [],
        // 弹窗显示状态
        dialogVisible: false,
        // 表单数据（新增/编辑用）
        form: {
            categoryId: null,
            parentId: null,
            categoryName: '',
            description: '',
            isActive: 1
        },
        // 弹窗标题
        formTitle: '分类信息',
        // 是否正在添加子类
        isAddingChild: false,
        // 父分类名称（用于添加子类时显示）
        parentCategoryName: ''
      }
    },
    mounted() {
      this.getTableData()
    },
    methods: {
      // 获取表格数据
      getTableData() {
        axios.get('/categories/page',{
          params:{
            current:this.current,
            size:this.size,
          }
        }).then(response => {
          if (response.data.code == 200){
            this.tableData = response.data.data.records;
            this.total = response.data.data.total;
            this.processTableData();
          }else {
            this.$message.error(response.data.message || '获取内容分类列表失败');
          }
        })
      },
      
      // 处理表格数据，构建树形结构
      processTableData() {
        // 先找出所有父分类 (parentId 为 null 或 0)
        const parentCategories = this.tableData.filter(item => !item.parentId);
        // 为每个父分类添加 children 属性
        parentCategories.forEach(parent => {
          parent.children = this.tableData.filter(child => child.parentId === parent.categoryId);
          parent.level = 0;
          if (parent.children && parent.children.length > 0) {
            parent.children.forEach(child => {
              child.level = 1;
            });
          }
        });
        this.processedTableData = parentCategories;
      },
      
      // 查询
      handleSearch() {
        this.current = 1
        this.getTableData()
      },
      // 重置查询条件
      resetSearch() {
        this.searchForm.dictType = ''
        this.searchForm.dictName = ''
        this.handleSearch()
      },
      // 分页 - 每页条数改变
      handleSizeChange(val) {
        this.size = val
        this.current = 1
        this.getTableData()
      },
      // 分页 - 当前页改变
      handleCurrentChange(val) {
        this.current = val
        this.getTableData()
      },
      // 多选框改变
      handleSelectionChange(val) {
        this.selectedRows = val
      },
      // 新增
      handleAdd() {
        this.isAddingChild = false;
        this.formTitle = '新增分类';
        this.dialogVisible = true;
        this.form = {
            categoryId: null,
            parentId: null,
            categoryName: '',
            description: '',
            isActive: 1
        };
      },
      
      // 添加子类
      handleAddChild(row) {
        this.isAddingChild = true;
        this.formTitle = '添加子分类';
        this.parentCategoryName = row.categoryName;
        this.dialogVisible = true;
        this.form = {
            categoryId: null,
            parentId: row.categoryId,
            categoryName: '',
            description: '',
            isActive: 1
        };
      },
      
      // 编辑
      handleEdit(row) {
        this.isAddingChild = false;
        this.formTitle = '编辑分类';
        this.dialogVisible = true;
        this.form = { ...row };
      },
      
      // 删除（单个）
      handleDelete(row) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.delete('/categories/delete',{
            params:{
              categoryId: row.categoryId
            }
          }).then( () =>{
            this.getTableData();
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
  
      // 状态切换处理函数
      handleSwitchChange(row, newStatus) {
        const action = newStatus === 0 ? '禁用' : '启用';
        const statusText = newStatus === 0 ? '禁用' : '正常';
        this.$confirm(`确定要${action}吗?`, '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          axios.post(`/categories/updateStatus?categoryId=${row.categoryId}&status=${row.isActive}`).then(response => {
            if (response.data.code == 200) {
              this.$message.success(`状态已更新为: ${statusText}`);
            } else {
              row.isActive = row.isActive === 1 ? 0 : 1;
              this.$message.error('状态更新失败: ' + response.data.message);
            }
          }).catch(error => {
            row.isActive = row.isActive === 1 ? 0 : 1;
            this.$message.error('请求失败: ' + error.message);
          });
        }).catch(() => {
          row.isActive = row.isActive === 1 ? 0 : 1;
          this.$message.info('操作已取消');
        });
      },
      
      // 保存（新增/编辑）
      handleSave() {
        // 简单校验
        if (!this.form.categoryName) {
          this.$message.error('请输入分类名称');
          return;
        }
        
        // 发送请求
        axios.post('/categories/saveOrUpdate', this.form)
            .then(response =>{
              if (response.data.code === 200) {
                this.$message.success(this.form.categoryId ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                // 刷新列表
                this.getTableData();
              } else {
                this.$message.error(response.data.message || '操作失败，请重试');
              }
            })
      }
    }
  }
  </script>
  
  <style scoped>
  .news-dict-container {
    padding: 20px;
  }
  .filter-card {
    margin-bottom: 20px;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  /* 树形表格样式 */
  .el-table /deep/ .el-table__row--level-1 {
    background-color: #f5f7fa;
  }
  </style>